package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"
)

// 用户界面获取商店信息
func usergetshopHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	if method == "POST" {

		var shops []Returnshopinfo2
		rows, err := db.Query(context.Background(), "SELECT shopname,imagename FROM shopping.p_shopinfo WHERE  state= 'pass'")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var shop Returnshopinfo2
			err := rows.Scan(&shop.Shopname, &shop.Imagename)
			if err != nil {
				fmt.Println(err)
			}
			shops = append(shops, shop)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(shops) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(shops))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(shops)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}

// 用户界面信息
func userinfoHandler(w http.ResponseWriter, r *http.Request) {
	method := r.Method
	if method == "POST" {
		var users []User
		var username struct {
			Username string `json:"username"`
		}
		err := json.NewDecoder(r.Body).Decode(&username)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		rows, err := db.Query(context.Background(), "SELECT * FROM shopping.p_user WHERE  username= $1", username.Username)
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {
			var user User
			err := rows.Scan(&user.UserType, &user.Username, &user.Phonenumber, &user.Idnumber, &user.Email, &user.Password)
			if err != nil {
				fmt.Println(err)
			}
			//fmt.Println(user)
			users = append(users, user)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(users) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d users\n", len(users))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(users)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return

		}
	} else if method == "PUT" {
		var user User
		err := json.NewDecoder(r.Body).Decode(&user)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		_, err = db.Exec(context.Background(), "UPDATE shopping.p_user SET role=$1, username = $2,phonenumber=$3,idnumber=$4,email=$5,password=$6 WHERE username=$7 AND role=$8", user.UserType, user.Username, user.Phonenumber, user.Idnumber, user.Email, user.Password, user.Username, user.UserType)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			fmt.Println(err)
			return
		}
		//返回成功的响应
		w.WriteHeader(http.StatusOK)
	}
}

// 用户获取商品信息
func usrgetgoodHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {

		var goods []Good
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_goods")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {

			var good Good
			err := rows.Scan(&good.Shopname, &good.Goodname, &good.Goodprice, &good.Goodcount)
			if err != nil {
				fmt.Println(err)
			}
			goods = append(goods, good)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(goods) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d goods\n", len(goods))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(goods)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}

}

// 用户购买商品
func usrbuygoodHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "PUT" {
		var good Purchaseinfo
		err := json.NewDecoder(r.Body).Decode(&good)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		//更新数据库的商品
		_, err = db.Exec(context.Background(), "UPDATE shopping.p_goods SET goodcount= goodcount-$1 WHERE  shopname=$2 and goodname=$3", good.Goodcount, good.Shopname, good.Goodname)
		if err != nil {
			fmt.Println("Purchase error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		//插入购买记录
		_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_purchase (username,shopname,goodname,goodcount,goodprice,cost) VALUES ($1,$2,$3,$4,$5,$6)", good.Username, good.Shopname, good.Goodname, good.Goodcount, good.Goodprice, good.Cost)
		//fmt.Println(good)
		if err != nil {
			fmt.Println("Purchase error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Good purchase successfully")
	}
}

// 用户提交评论
func givecommentHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		var comment Comment
		err := json.NewDecoder(r.Body).Decode(&comment)
		if err != nil {
			fmt.Println(err)
			http.Error(w, err.Error(), http.StatusBadRequest)
		}
		var tempdate time.Time
		tempdate, err = time.Parse("2006-01-02 15:04:05", comment.Time)
		if err != nil {
			log.Fatalf("Error parsing time: %v", err)
		}
		// fmt.Println(comment.Time)
		// fmt.Println(tempdate)
		//插入评论
		_, err = db.Exec(context.Background(), "INSERT INTO shopping.p_comment (username,shopname,goodname,text,time) VALUES ($1,$2,$3,$4,$5)", comment.Username, comment.Shopname, comment.Goodname, comment.Text, tempdate)
		if err != nil {
			fmt.Println("Comment error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 返回一个成功的响应
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, "Comment give successfully")
	}
}

// 用户获取评论信息
func usrgetcommentHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		var comments []Comment
		// 查询数据库
		rows, err := db.Query(context.Background(), "SELECT *FROM shopping.p_comment")
		if err != nil {
			fmt.Println(err)
		}
		defer rows.Close()
		for rows.Next() {
			var tempdate time.Time
			var comment Comment
			err := rows.Scan(&comment.Username, &comment.Shopname, &comment.Goodname, &comment.Text, &tempdate)
			if err != nil {
				fmt.Println(err)
			}
			comment.Time = tempdate.Format("2006-01-02 15:04:05")
			// fmt.Println(comment.Time)
			// fmt.Println(tempdate)
			comments = append(comments, comment)
		}
		if err := rows.Err(); err != nil {
			fmt.Println("Rows iteration error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 检查是否查询到了数据
		if len(comments) == 0 {
			fmt.Println("No data found")
		} else {
			fmt.Printf("Found %d comments\n", len(comments))
		}
		// 设置响应头部，指定内容类型为JSON
		w.Header().Set("Content-Type", "application/json")
		// 将User切片编码为JSON格式并发送给客户端
		jsonData, err := json.Marshal(comments)
		if err != nil {
			fmt.Println("JSON marshal error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 将JSON数据写入响应体
		_, err = w.Write(jsonData)
		if err != nil {
			fmt.Println("Response write error:", err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
}
